package g

import (
	"sync"

	"github.com/BurntSushi/toml"
)

/*
[rpc]
host = "127.0.0.1"
port = 5020

[fhe_search]
encrypt_type = "soft_encrypt" # or "card_encrypt". 软加密或者卡加密，没有默认值，必须指定，否则程序无法运行。
secret_key_path = "../huangheng20240529/"
*/

var (
	c     *Config
	cOnce sync.Once
)

type Config struct {
	RpcConfig       RpcConfig       `toml:"rpc"`
	FheSearchConfig FheSearchConfig `toml:"fhe_search"`
}

type RpcConfig struct {
	Host string `toml:"host"`
	Port int    `toml:"port"`
}

type FheSearchConfig struct {
	EncryptType   string `toml:"encrypt_type"`
	SecretKeyPath string `toml:"secret_key_path"`
}

func ReadConfig(filePath string) {
	cOnce.Do(func() {
		config := Config{}
		_, err := toml.DecodeFile(filePath, &config)
		if err != nil {
			panic(err)
		}
		// config检查:
		// 1 path必须以正斜线结尾
		secretKeyPath := config.FheSearchConfig.SecretKeyPath
		if secretKeyPath[len(secretKeyPath)-1] != '/' {
			panic("file_base_path and secret_key_path must end with '/'")
		}
		// 2 encrypt_type 仅支持两个值 soft_encrypt or card_encrypt
		encryptType := config.FheSearchConfig.EncryptType
		if !(encryptType == "soft_encrypt" || encryptType == "card_encrypt") {
			panic("encrypt_type must be 'soft_encrypt' or 'card_encrypt', but you give " + encryptType)
		}
		c = &config
	})
}

func GetConfig() *Config {
	if c == nil {
		const DefaultConfigFilePath = "cfg.toml"
		ReadConfig(DefaultConfigFilePath)
	}
	return c
}
